#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 57;
char lis[maxn][maxn];
int N;
bool vis[maxn][maxn][maxn];
struct Node {int p1, p2, p3, dis;
Node() {} 
Node(int p1, int p2, int p3, int dis):p1(p1), p2(p2), p3(p3), dis(dis) {}
bool judge(){if(p1 == p2 && p2 == p3) return true; else return false;}
};
int bfs(int p1, int p2, int p3){
	memset(vis, 0, sizeof(vis));
	vis[p1][p2][p3] = 1;
	queue<Node> Q;
	Q.push(Node(p1, p2, p3, 0));
	while(!Q.empty()){
		Node rig = Q.front(); Q.pop();
		if(rig.judge()){
			return rig.dis;
		}
		for(int i = 1; i<= N; i ++){
			if(rig.p1 != i && lis[rig.p1][i] == lis[rig.p2][rig.p3]){
				if(!vis[i][rig.p2][rig.p3]) Q.push(Node(i, rig.p2, rig.p3, rig.dis + 1)), vis[i][rig.p2][rig.p3] = 1;
			}
			if(rig.p2 != i && lis[rig.p2][i] == lis[rig.p1][rig.p3]){
				if(!vis[rig.p1][i][rig.p3]) Q.push(Node(rig.p1, i, rig.p3, rig.dis + 1)), vis[rig.p1][i][rig.p3] = 1;
;
			}
			if(rig.p3 != i && lis[rig.p3][i] == lis[rig.p1][rig.p2]){
				if(!vis[rig.p1][rig.p2][i]) Q.push(Node(rig.p1, rig.p2, i, rig.dis + 1)), vis[rig.p1][rig.p2][i] = 1;

			}
		}
	}
	return -1;
}
int main()
{
	int p1, p2, p3;
	ios::sync_with_stdio(false);
	while(cin >> N && N){
		cin >> p1 >> p2>> p3;
		for(int i = 1; i <= N; i ++)
			for(int j = 1; j <= N; j ++)
				cin >> lis[i][j];
		int ans = bfs(p1, p2, p3);
		if(ans == -1) cout << "impossible\n";
		else cout << ans << endl;
	}
	return 0;

}
